//
//  BDPromotionViewController.m
//  手机号码验证
//
//  Created by Chuz NetTech on 17/9/11.
//  Copyright © 2017年 Chuz NetTech. All rights reserved.
//

#import "BDPromotionViewController.h"
#import <CoreImage/CoreImage.h>
#import "BDUserModel.h"

@interface BDPromotionViewController (){
    BOOL clickGetButton;
    UIColor *finishColor;
}
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UITextField *validationTextField;
@property (nonatomic, strong) UIButton *rightButton;
@property (nonatomic, strong) UIButton *determineButton;
@end

@implementation BDPromotionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = ASLocalizedString(@"推广");
    [self createUI];
    
    [self requestData];
}

-(void)requestData{
    RACSignal *getEnable =[RACSignal combineLatest:@[self.textField.rac_textSignal] reduce:^id _Nullable{
        return @(self.textField.text.length == 11);
    }];
    
    RAC(self.rightButton, userInteractionEnabled) = getEnable;
    [getEnable subscribeNext:^(id  _Nullable x) {
        if (clickGetButton == NO) {
            self.rightButton.backgroundColor = [x boolValue] ? kCodeButtonColor : kNOValidColor;
            // BDLog(ASLocalizedString(@"获取验证码按钮是否能按：%d"), self.rightButton.userInteractionEnabled);
        }else{
            finishColor = [x boolValue] ? kCodeButtonColor : kNOValidColor;
        }
    }];
    
    
    RACSignal *getSendSignal = [self.rightButton rac_signalForControlEvents:UIControlEventTouchUpInside];
    [getSendSignal subscribeNext:^(id  _Nullable x) {
        // BDLog(ASLocalizedString(@"点击了发送验证的按钮"));
        clickGetButton = YES;
        self.rightButton.backgroundColor = kNOValidColor;
        _rightButton.userInteractionEnabled = NO;
        
        NSDictionary *para = @{@"mobile":self.textField.text};
        NSString *url = [NSString stringWithFormat:@"%@sms", KBDBaseURL];
        
        RACCommand *getCodeCommand = [BDNetworkingServer yy_POST:url parameters:para validation:nil automaticProcessingError:NO];
        RACSignal *getCodeSignal = [getCodeCommand execute:nil];
        
        [[getCodeSignal deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id  _Nullable x) {
            [self.validationTextField becomeFirstResponder];
            
            @weakify(self);
            __block NSInteger number = 60;
            NSInteger numberLimit = number;
            RACSignal *timeSignal = [[[[[RACSignal interval:1.0f onScheduler:[RACScheduler mainThreadScheduler]] take:numberLimit] startWith:[NSDate date]] map:^id(NSDate *date) {
                @strongify(self);
                if (number == 0) {
                    [self.rightButton setTitle:ASLocalizedString(@"重新发送")forState:UIControlStateNormal];
                    self.rightButton.userInteractionEnabled = YES;
                    clickGetButton = NO;
                    self.rightButton.backgroundColor = finishColor == nil ? kCodeButtonColor : finishColor;
                    return @YES;
                }else{
                    [self.rightButton setTitle:[NSString stringWithFormat:ASLocalizedString(@"剩余%ld秒"), number] forState:UIControlStateNormal];
                    //                    // BDLog(ASLocalizedString(@"按钮文本是什么：%@"), [NSString stringWithFormat:ASLocalizedString(@"剩余%ld秒"), number]);
                    number--;
                    return @NO;
                }
            }] takeUntil:self.rac_willDeallocSignal];
            
            _rightButton.rac_command = [[RACCommand alloc]initWithEnabled:timeSignal signalBlock:^RACSignal *(id input) {
                number = numberLimit;
                return timeSignal;
            }];
        }];
        
        [getSendSignal subscribeError:^(NSError * _Nullable error) {
            [MBManager showCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]] title:ASLocalizedString(@"发送验证码失败，请稍后再试")clickHidden:NO clickBlock:nil];
            [self.rightButton setTitle:ASLocalizedString(@"重新发送")forState:UIControlStateNormal];
            self.rightButton.userInteractionEnabled = YES;
            clickGetButton = NO;
            self.rightButton.backgroundColor = finishColor == nil ? kCodeButtonColor : finishColor;
        }];
    }];
    
    [[self.determineButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        
        NSDictionary *dict = @{@"mobile":self.textField.text,@"code":self.validationTextField.text};
        NSString *url = [NSString stringWithFormat:@"%@MLMRelates",KBDBaseURL];
        
        NSString *headValid = [BDUserModel getHeaderValidation];
        RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:dict validation:headValid automaticProcessingError:YES] execute:nil];
        [signal subscribeNext:^(id  _Nullable y) {
            [MBManager showBriefAlert:ASLocalizedString(@"推广成功")clickHidden:YES clickBlock:nil];
        }];
        
        [signal subscribeError:^(NSError * _Nullable error) {
            if (error.code == 40001) {
                [MBManager showBriefAlert:ASLocalizedString(@"该用户已经成为别人的推广对象")clickHidden:YES clickBlock:nil];
            }
        }];

    }];


}

-(void)createUI{
    UIView *bgView = [[UIView alloc] init];
    bgView.top = kBDTopHeight;
    bgView.left = 0;
    bgView.width = kBDScreenWidth;
    bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgView];
    
    UIView *textFieldView = [[UIView alloc] initWithFrame:CGRectMake(10, 20, kBDScreenWidth - 20, 45)];
    textFieldView.layer.cornerRadius = 5;
    textFieldView.layer.masksToBounds = YES;
    textFieldView.layer.borderColor = [UIColor colorWithHexString:@"cccccc"].CGColor;
    textFieldView.layer.borderWidth = 1.0;
    [bgView addSubview:textFieldView];
    
    UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 15, 70, 15)];
    leftLabel.text = ASLocalizedString(@"手机号码");
    leftLabel.font = [UIFont systemFontOfSize:15];
    leftLabel.textColor = [UIColor colorWithHexString:@"4c4c4c"];
    [textFieldView addSubview:leftLabel];
    
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(80, 0, kBDScreenWidth - 20 - 80 - 80, 45)];
    self.textField.borderStyle = UITextBorderStyleNone;
    self.textField.placeholder = ASLocalizedString(@"请输入邀请好友手机号码");
    [textFieldView addSubview:self.textField];
    
    
    self.rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _rightButton.frame = CGRectMake(kBDScreenWidth - 20 - 80, 0, 80, 45);
    _rightButton.backgroundColor = KBDColorBlue;
    [_rightButton setTitle:ASLocalizedString(@"获取验证码")forState:UIControlStateNormal];
    _rightButton.titleLabel.font = [UIFont systemFontOfSize:12];
    _rightButton.layer.cornerRadius = 5;
    [textFieldView addSubview:_rightButton];
    
    UIView *validationView = [[UIView alloc] initWithFrame:CGRectMake(10,20 + 45 + 10, kBDScreenWidth - 20, 45)];
    validationView.layer.cornerRadius = 5;
    validationView.layer.masksToBounds = YES;
    validationView.layer.borderColor = [UIColor colorWithHexString:@"cccccc"].CGColor;
    validationView.layer.borderWidth = 1.0;
    [bgView addSubview:validationView];
    
    UILabel *validationLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 15, 70, 15)];
    validationLabel.text = ASLocalizedString(@"验证码");
    validationLabel.font = [UIFont systemFontOfSize:15];
    validationLabel.textColor = [UIColor colorWithHexString:@"4c4c4c"];
    [validationView addSubview:validationLabel];
    
    self.validationTextField = [[UITextField alloc] initWithFrame:CGRectMake(80, 0, kBDScreenWidth - 20 - 80, 45)];
    self.validationTextField.borderStyle = UITextBorderStyleNone;
    self.validationTextField.placeholder = ASLocalizedString(@"请输入验证码");
    [validationView addSubview:self.validationTextField];
    
    
    self.determineButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _determineButton.top = validationView.bottom + 10;
    _determineButton.left = 10;
    _determineButton.size = CGSizeMake(kBDScreenWidth - 20, 45);
    _determineButton.layer.cornerRadius = 5;
    _determineButton.backgroundColor = KBDColorBlue;
    [_determineButton setTitle:ASLocalizedString(@"确    定")forState:UIControlStateNormal];
    [bgView addSubview:_determineButton];
 
    bgView.height = _determineButton.bottom + 30;
    
    UIView *centerbgView = [[UIView alloc] init];
    centerbgView.top = bgView.bottom + 10;
    centerbgView.left = 0;
    centerbgView.width = kBDScreenWidth;
    centerbgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:centerbgView];
    
    UILabel *promotionLabel = [[UILabel alloc] init];
    promotionLabel.text = ASLocalizedString(@"我的推广二维码");
    promotionLabel.textColor = [UIColor colorWithHexString:@"4c4c4c"];
    promotionLabel.font = [UIFont systemFontOfSize:15];
    [promotionLabel sizeToFit];
    promotionLabel.top = 15;
    promotionLabel.left = 10;
    [centerbgView addSubview:promotionLabel];
    
    
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 滤镜恢复默认设置
    [filter setDefaults];
    
    // 2. 给滤镜添加数据
    NSString *string = @"what the fuck? hello man, fuck you.";
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    // 使用KVC的方式给filter赋值
    [filter setValue:data forKeyPath:@"inputMessage"];
    
    // 3. 生成二维码
    CIImage *image = [filter outputImage];
    
    
    // 4. 显示二维码
    UIImageView *codeImageView = [[UIImageView alloc] init];
    codeImageView.top = promotionLabel.bottom + 20;
    codeImageView.size = CGSizeMake(125, 125);
    codeImageView.centerX = centerbgView.centerX;
    [centerbgView addSubview:codeImageView];
    
    codeImageView.image = [self createNonInterpolatedUIImageFormCIImage:image withSize:125];
    
    
    UILabel *introduceLabel = [[UILabel alloc] init];
    introduceLabel.top = codeImageView.bottom + 20;
    introduceLabel.text = ASLocalizedString(@"打开微信·扫描二维码·快速邀请");
    introduceLabel.textColor = [UIColor colorWithHexString:@"4c4c4c"];
    introduceLabel.font = [UIFont systemFontOfSize:15];
    [introduceLabel sizeToFit];
    introduceLabel.centerX = codeImageView.centerX;
    [centerbgView addSubview:introduceLabel];
    
    centerbgView.height = introduceLabel.bottom + 45;
}

- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
